<?php

namespace addons\sum\controller\video;

use addons\sum\controller\Common;
use addons\sum\service\Wallet as WalletService;
use app\admin\model\sum\user\User as UserModel;
use app\admin\model\sum\video\Episodes as EpisodesModel;
use app\admin\model\sum\video\Log as VideoLogModel;
use app\admin\model\sum\video\Order as VideoOrderModel;
use app\admin\model\sum\video\Like as VideoLikeModel;
use app\admin\model\sum\video\Favorite as VideoFavoriteModel;
use app\admin\model\sum\video\Video as VideoModel;
use think\Db;

class Video extends Common
{

    protected $noNeedLogin = ['index','detail','recommend'];
    protected $noNeedRight = ['*'];

    /**
     * 短剧列表
     */
    public function index()
    {
        $langSlug=$this->langSlug;

        $list_rows = $this->request->param('list_rows', 20);
        $keyword = $this->request->param('keyword', '');
        $category_id = $this->request->param('category_id');
        $sort = $this->request->param('sort','weigh');
        $order = $this->request->param('order','desc');

        $query=new VideoModel();
        $query=$query->where('status','up')->where('lang',$langSlug);
        if ($keyword) {
            $query=$query->where('title', 'like', '%' . $keyword . '%');
        }
        if($category_id){
            $query= $query->whereRaw("find_in_set($category_id, category_ids)");
        }
        $records=$query->order('weigh DESC')->paginate($list_rows);
        $this->success(__('获取成功'),$records);
    }

    /**
     * 短剧详情
     */
    public function detail(){
        $user = auth_user();
        $id = $this->request->param('id');
        // 短剧
        $video=VideoModel::where('id',$id)->where('status','up')->find();
        // 隐藏无用字段
        $video->hidden(['fake_likes', 'fake_favorites', 'fake_shares', 'fake_views','fake_comments']);
        $video->hidden(['likes', 'favorites', 'shares', 'views','comments']);
        $video->hidden(['image','sales']);
        // 剧集
        $episodes=EpisodesModel::where('video_id',$video['id'])->where('status','normal')->order('weigh','asc')->select();
        // 免费集数
        $free_episodes_num=EpisodesModel::where('video_id',$video['id'])->where('status','normal')->where('price',0)->count();
        // 预处理短剧-用户相关字段
        $video['is_buy']=0;// 是否整剧购买
        $video['is_like']=0;// 是否点赞
        $video['is_favorite']=0;// 是否收藏
        $video['free_episodes_num']=$free_episodes_num;// 免费集数

        $order_video=null;
        $is_vip=false; // 用户是否VIP
        $like_episode_ids=[];
        $favorite_episode_ids=[];
        $order_episode_ids=[];
        if($user){
            $is_vip=UserModel::where('id', $user->id)->find()->is_vip; // 用户是否VIP
            // 是否有整剧购买的订单
            $order_video=VideoOrderModel::where('video_id',$video['id'])->where('user_id',$user['id'])->where('type',2)->find();
            if($order_video){
                $video['is_buy']=1;
            }
            // 是否有整剧点赞
            $order_like=VideoLikeModel::where('video_id',$video['id'])->where('user_id',$user['id'])->where('type',2)->find();
            if($order_like){
                $video['is_like']=1;
            }
            // 是否有整剧收藏
            $order_favorite=VideoFavoriteModel::where('video_id',$video['id'])->where('user_id',$user['id'])->where('type',2)->find();
            if($order_favorite){
                $video['is_favorite']=1;
            }
            // 单集点赞的剧集ids
            $like_episode_ids=VideoLikeModel::where('video_id',$video['id'])->where('user_id',$user['id'])->where('type',1)->column('episode_id');
            // 单集收藏的剧集ids
            $favorite_episode_ids=VideoFavoriteModel::where('video_id',$video['id'])->where('user_id',$user['id'])->where('type',1)->column('episode_id');
            // 单集购买的剧集ids
            $order_episode_ids=VideoOrderModel::where('video_id',$video['id'])->where('user_id',$user['id'])->where('type',1)->column('episode_id');
        }
        // 处理剧集-额外字段
        foreach ($episodes as &$item){
            $item['is_like']=0;// 是否点赞
            $item['is_favorite']=0;// 是否收藏
            $item['is_lock']=1;// 是否锁集 1锁住不能看 0没锁可以看
            if(in_array($item['id'],$like_episode_ids)){
                $item['is_like']=1;// 是否点赞
            }
            if(in_array($item['id'],$favorite_episode_ids)){
                $item['is_favorite']=1;// 是否点赞
            }
            if($item['price']==0){// 剧集免费
                $item['is_lock']=0;// 是否锁集
            }
            if($is_vip){// 用户是vip
                $item['is_lock']=0;// 是否锁集
            }
            if($order_video){// 整剧购买
                $item['is_lock']=0;// 是否锁集
            }
            $item['order_video']=$order_video;
            if(in_array($item['id'],$order_episode_ids)){// 单集购买
                $item['is_lock']=0;// 是否锁集
            }
            // 处理视频链接
            if($item['is_lock']==0){
                $item['video_url'] = $item['video_url']?cdnurl($item['video_url'], true):'';
            }else{
                $item['video_url']='';
            }
            // 隐藏无用字段
            $item->hidden(['fake_likes', 'fake_favorites', 'fake_shares', 'fake_views','fake_comments']);
            $item->hidden(['likes', 'favorites', 'shares', 'views','comments']);
            $item->hidden(['image','duration','sales']);
        }
        $return=[];
        $return['video']=$video;
        $return['episodes']=$episodes;
        $this->success(__('获取成功'),$return);
    }

    /**
     * 推荐剧集列表
     */
    public function recommend()
    {
        $langSlug=$this->langSlug;
        $user = auth_user();
        $list_rows = $this->request->param('list_rows', 20);
        // 推荐的-免费的-剧集
        $episodes=EpisodesModel::where('price',0)->where('is_recommend',1)->where('status','normal')->whereExists(function ($q)use($langSlug){
            $self_name = (new EpisodesModel())->getQuery()->getTable();
            $item_name = (new VideoModel())->getQuery()->getTable();
            $q->table($item_name)->where('id=' . $self_name . '.video_id')
                ->where('lang', $langSlug)
                ->whereNull('deletetime');
        })->order('weigh','asc')->paginate($list_rows);

//        echo EpisodesModel::getLastSql();

        $episodes->each(function ($item)use($user){
            $item['is_like']=0;// 是否点赞
            $item['is_favorite']=0;// 是否收藏
            if($user){
                // 单集点赞的剧集
                $like_episode=VideoLikeModel::where('episode_id',$item['id'])->where('user_id',$user['id'])->where('type',1)->find();
                if($like_episode){
                    $item['is_like']=1;// 是否点赞
                }
                // 单集收藏的剧集
                $favorite_episode=VideoFavoriteModel::where('episode_id',$item['id'])->where('user_id',$user['id'])->where('type',1)->find();
                if($favorite_episode){
                    $item['is_favorite']=1;// 是否点赞
                }
            }
            $video=VideoModel::where('id',$item['video_id'])->find();
            $item['video'] =$video;
            $item['video_url'] = $item['video_url']?cdnurl($item['video_url'], true):'';
            // 隐藏无用字段
            $item->hidden(['fake_likes', 'fake_favorites', 'fake_shares', 'fake_views','fake_comments']);
            $item->hidden(['likes', 'favorites', 'shares', 'views','comments']);
            $item->hidden(['image','duration','sales']);
        });

        // 触发任务事件-评论视频
        $data = ['event' => 'task_video_comment', 'user' => $user];
        \think\Hook::listen('task_event', $data);

        $this->success(__('获取成功'),$episodes);
    }

    /**
     * 购买短剧
     * @return void
     */
    public function buy(){
        $user = auth_user();
        $video_id = $this->request->param('video_id');
        $episode_id = $this->request->param('episode_id',0);
        $type = $this->request->param('type');//购买类型1=单集购买,2=整剧购买
        $is_vip=UserModel::where('id', $user->id)->find()->is_vip; // 用户是否VIP
        if(!$video_id){
            $this->error(__('参数错误'));
        }
        if(!in_array($type,[1,2])){
            $this->error(__('参数错误'));
        }
        $pay_money=0;
        // 短剧
        $video=VideoModel::where('id',$video_id)->where('status','up')->find();
        if(!$video){
            $this->error(__('该短剧不存在'));
        }
        if($is_vip){
            $this->error(__('你是vip,可享受免费观看'));
        }
        // 是否有整剧购买的订单
        $order_video=VideoOrderModel::where('video_id',$video['id'])->where('user_id',$user['id'])->where('type',2)->find();
        if($order_video){
            $this->error(__('你已购买该剧'));
        }
        if($type==2){// 整剧购买
            $pay_money=$video['price'];
            $episode_id=0;
            $video_url=null;
        }else{// 单集购买
            $episode=EpisodesModel::where('video_id',$video['id'])->where('id',$episode_id)->where('status','normal')->find();
            if(!$episode){
                $this->error(__('该剧集不存在'));
            }
            // 是否有整剧购买的
            $order_video_episode=VideoOrderModel::where('video_id',$video['id'])->where('episode_id',$episode_id)->where('user_id',$user['id'])->where('type',1)->find();
            if($order_video_episode){
                $this->error(__('你已购买该集'));
            }
            $pay_money=$episode['price'];
            $video_url=$episode['video_url']?cdnurl($episode['video_url'], true):'';
        }
        $order= Db::transaction(function () use ($pay_money,$user,$type,$video_id,$episode_id) {
            //添加订单记录
            $order=new VideoOrderModel();
            $order->user_id=$user['id'];
            $order->type=$type;
            $order->video_id=$video_id;
            $order->episode_id=$episode_id;
            $order->save();
            if($pay_money>0){
                // 扣除用户积分
                WalletService::change($user, 'score', -$pay_money, 'video_pay',[
                    'order_id'=>$order->id
                ]);
            }
            return $order;
        });
        $this->success(__('购买成功'),$video_url);
    }

    /**
     * 增加播放记录
     * @return void
     */
    public function log(){
        $user = auth_user();
        $video_id = $this->request->param('video_id');
        $episode_id = $this->request->param('episode_id');
        if(!$video_id){
            $this->error(__('参数错误'));
        }
        if(!$episode_id){
            $this->error(__('参数错误.'));
        }
        $episode=EpisodesModel::where('id',$episode_id)->where('video_id',$video_id)->find();
        if(!$episode){
            $this->error(__('参数错误'));
        }
        if($user){
            $video_log=VideoLogModel::where('user_id',$user['id'])->where('video_id',$video_id)->where('type',2)->find();
            if($video_log){
                $video_log->episode_id=$episode_id;
                $video_log->episode_weigh=$episode['weigh'];
                $video_log->save();
            }else{
                $video_log=new VideoLogModel();
                $video_log->user_id=$user['id'];
                $video_log->video_id=$video_id;
                $video_log->episode_id=$episode_id;
                $video_log->episode_weigh=$episode['weigh'];
                $video_log->type=2;
                $video_log->save();
            }

            $episode_log=VideoLogModel::where('user_id',$user['id'])->where('video_id',$video_id)->where('episode_id',$episode_id)->where('type',1)->find();
            if(!$episode_log){
                $episode_log=new VideoLogModel();
                $episode_log->user_id=$user['id'];
                $episode_log->video_id=$video_id;
                $episode_log->episode_id=$episode_id;
                $episode_log->episode_weigh=$episode['weigh'];
                $episode_log->type=1;
                $episode_log->save();
            }

            // 触发任务事件-点赞视频
            $data = ['event' => 'task_video_watch', 'user' => $user];
            \think\Hook::listen('task_event', $data);
        }

        $this->success(__('操作成功'));
    }

    /**
     * 短剧观看记录按剧
     * @return void
     */
    public function loglist(){
        $user = auth_user();
        $today_date=strtotime('today');
        $yesterday_date=strtotime('yesterday');
        $list_rows = $this->request->param('list_rows', 20);
        // today 今天的观看记录
        $today_list=VideoLogModel::where('updatetime',">=",$today_date)->where('user_id',$user['id'])->where('type',2)->select();
        foreach ($today_list as $t_item){
            $t_item['video']=VideoModel::where('id',$t_item['video_id'])->find();
        }
        // yesterday
        $yesterday_list=VideoLogModel::where('updatetime',">=",$yesterday_date)->where('updatetime',"<",$today_date)->where('user_id',$user['id'])->where('type',2)->select();
        foreach ($yesterday_list as $y_item){
            $y_item['video']=VideoModel::where('id',$y_item['video_id'])->find();
        }
        // earlier
        $earlier_list=VideoLogModel::where('updatetime',"<",$yesterday_date)->where('user_id',$user['id'])->where('type',2)->paginate($list_rows);
        $earlier_list->each(function ($e_item){
            $e_item['video']=VideoModel::where('id',$e_item['video_id'])->find();
        });
        $return=[];
        $return['today']=$today_list;
        $return['yesterday']=$yesterday_list;
        $return['earlier']=$earlier_list;
        $this->success(__('获取成功'),$return);
    }


    /**
     * 购买记录
     * @return void
     */
    public function buylist(){
        $user = auth_user();
        $list_rows = $this->request->param('list_rows', 20);
        $records=VideoModel::where('status','up')->whereExists(function ($query)use($user){
            $self_name = (new VideoModel())->getQuery()->getTable();
            $item_name = (new VideoOrderModel())->getQuery()->getTable();
            $query->table($item_name)->where('video_id=' . $self_name . '.id')
                ->where('type', 2)
                ->where('user_id', $user['id']);
        })->paginate($list_rows);
        $this->success(__('获取成功'),$records);
    }


    /**
     * 点赞短剧
     * @return void
     */
    public function like(){
        $user = auth_user();
        $video_id = $this->request->param('video_id');
        $episode_id = $this->request->param('episode_id',0);
        $type = $this->request->param('type');//类型1=单集,2=整剧
        if(!$video_id){
            $this->error(__('参数错误'));
        }
        if(!in_array($type,[1,2])){
            $this->error(__('参数错误'));
        }
        // 短剧
        $video=VideoModel::where('id',$video_id)->where('status','up')->find();
        if(!$video){
            $this->error(__('该短剧不存在'));
        }
        if($type==2){
            $episode_id=0;
            $episode=null;
        }else{
            $episode=EpisodesModel::where('id',$episode_id)->where('video_id',$video_id)->find();
            if(!$episode){
                $this->error(__('参数错误'));
            }
        }
        $record=VideoLikeModel::where('video_id',$video['id'])->where('user_id',$user['id'])->where('type',$type)->where('episode_id',$episode_id)->find();
        if($record){
            if($episode){
                $episode->likes=$episode->likes-1;
                $episode->save();
            }
            $record->delete();
        }else{
            if($episode){
                $episode->likes=$episode->likes+1;
                $episode->save();
            }
            $record=new VideoLikeModel();
            $record->user_id=$user['id'];
            $record->type=$type;
            $record->video_id=$video_id;
            $record->episode_id=$episode_id;
            $record->save();

            // 触发任务事件-点赞视频
            $data = ['event' => 'task_video_like', 'user' => $user];
            \think\Hook::listen('task_event', $data);
        }
        $this->success(__('操作成功'));
    }
    /**
     * 点赞记录
     * @return void
     */
    public function likelist(){
        $user = auth_user();
        $list_rows = $this->request->param('list_rows', 20);
        $records=VideoModel::where('status','up')->whereExists(function ($query)use($user){
            $self_name = (new VideoModel())->getQuery()->getTable();
            $item_name = (new VideoLikeModel())->getQuery()->getTable();
            $query->table($item_name)->where('video_id=' . $self_name . '.id')
                ->where('type', 2)
                ->where('user_id', $user['id']);
        })->paginate($list_rows);
        $this->success(__('获取成功'),$records);
    }


    /**
     * 收藏短剧
     * @return void
     */
    public function favorite(){
        $user = auth_user();
        $video_id = $this->request->param('video_id');
        $episode_id = $this->request->param('episode_id',0);
        $type = $this->request->param('type');//类型1=单集,2=整剧
        if(!$video_id){
            $this->error(__('参数错误'));
        }
        if(!in_array($type,[1,2])){
            $this->error(__('参数错误'));
        }
        // 短剧
        $video=VideoModel::where('id',$video_id)->where('status','up')->find();
        if(!$video){
            $this->error(__('该短剧不存在'));
        }
        if($type==2){
            $episode_id=0;
            $episode=null;
        }else{
            $episode=EpisodesModel::where('id',$episode_id)->where('video_id',$video_id)->find();
            if(!$episode){
                $this->error(__('参数错误'));
            }
        }
        $record=VideoFavoriteModel::where('video_id',$video['id'])->where('user_id',$user['id'])->where('type',$type)->where('episode_id',$episode_id)->find();
        if($record){
            if($episode){
                $episode->favorites=$episode->favorites-1;
                $episode->save();
            }
            $record->delete();
        }else{
            if($episode){
                $episode->favorites=$episode->favorites+1;
                $episode->save();
            }
            $record=new VideoFavoriteModel();
            $record->user_id=$user['id'];
            $record->type=$type;
            $record->video_id=$video_id;
            $record->episode_id=$episode_id;
            $record->save();

            //单集收藏时添加一条整剧收藏的记录-用于收藏记录的显示
            if($type==1){
                $record_all=VideoFavoriteModel::where('video_id',$video['id'])->where('user_id',$user['id'])->where('type',2)->find();
                if(!$record_all){
                    $record_all=new VideoFavoriteModel();
                    $record_all->user_id=$user['id'];
                    $record_all->type=2;
                    $record_all->video_id=$video_id;
                    $record_all->episode_id=0;
                    $record_all->save();
                }
            }

        }

        $this->success(__('操作成功'));
    }
    /**
     * 收藏记录
     * @return void
     */
    public function favoritelist(){
        $user = auth_user();
        $list_rows = $this->request->param('list_rows', 20);
        $records=VideoModel::where('status','up')->whereExists(function ($query)use($user){
            $self_name = (new VideoModel())->getQuery()->getTable();
            $item_name = (new VideoFavoriteModel())->getQuery()->getTable();
            $query->table($item_name)->where('video_id=' . $self_name . '.id')
                ->where('type', 2)
                ->where('user_id', $user['id']);
        })->paginate($list_rows);
        $this->success(__('获取成功'),$records);
    }

    /**
     * 分享短剧
     * @return void
     */
    public function share(){
        $user = auth_user();
        $video_id = $this->request->param('video_id');
        $episode_id = $this->request->param('episode_id',0);
        $type = $this->request->param('type');//类型1=单集,2=整剧
        if(!$video_id){
            $this->error(__('参数错误'));
        }
        if(!in_array($type,[1,2])){
            $this->error(__('参数错误'));
        }
        // 短剧
        $video=VideoModel::where('id',$video_id)->where('status','up')->find();
        if(!$video){
            $this->error(__('该短剧不存在'));
        }
        if($type==2){
            $episode_id=0;
            $episode=null;
        }else{
            $episode=EpisodesModel::where('id',$episode_id)->where('video_id',$video_id)->find();
            if(!$episode){
                $this->error(__('参数错误'));
            }else{
                // 增加分享数
                $episode->shares=$episode->shares+1;
                $episode->save();
            }
        }


        // 触发任务事件-分享视频
        $data = ['event' => 'task_video_share', 'user' => $user];
        \think\Hook::listen('task_event', $data);

        $this->success(__('操作成功'));
    }
    public function task_video_watch(){
        $user = auth_user();
        // 触发任务事件-观看视频5分钟
        $data = ['event' => 'task_video_watch', 'user' => $user];
        \think\Hook::listen('task_event', $data);
        $this->success(__('操作成功'));
    }

}
